package com.myharos.fingerguessing;

import ohos.aafwk.ability.Ability;
import ohos.aafwk.ability.IAbilityConnection;
import ohos.aafwk.content.Intent;
import ohos.aafwk.content.Operation;
import ohos.app.Context;
import ohos.bundle.ElementName;
import ohos.distributedschedule.interwork.DeviceInfo;
import ohos.distributedschedule.interwork.DeviceManager;
import ohos.rpc.*;

import java.util.List;

public class connect extends Ability {
    private final connectRemote remote = new connectRemote();
    private Context context;

    //对方设备与本service沟通的remote
    public static IRemoteObject otherRemote;

    //本地FA与service沟通的remote
    private static IRemoteObject localRemote;

    @Override
    public void onStart(Intent intent) {
        System.out.println("service start");
        super.onStart(intent);
        context = this;
    }

    @Override
    public void onBackground() {
        super.onBackground();
    }

    @Override
    public void onStop() {
        super.onStop();
    }

    @Override
    public void onCommand(Intent intent, boolean restart, int startId) {
    }

    @Override
    public IRemoteObject onConnect(Intent intent) {
        return remote.asObject();
    }

    @Override
    public void onDisconnect(Intent intent) {
    }

    private void sendToFA(int code, String dataString, IRemoteObject remote) throws Exception {
        //向FA发送数据
        MessageParcel data = MessageParcel.obtain();
        MessageParcel reply = MessageParcel.obtain();
        MessageOption option = new MessageOption();
        data.writeString(dataString);
        remote.sendRequest(code, data, reply, option);
        reply.reclaim();
        data.reclaim();
    }

    class connectRemote extends RemoteObject implements IRemoteBroker{
        connectRemote(){
            super("connectRemote");
        }

        @Override
        public boolean onRemoteRequest(int code, MessageParcel data, MessageParcel reply, MessageOption option) {
            String msg = data.readString();
            switch (code){
                case 0:{
                    // connect
                    // 连接对方设备
                    List<DeviceInfo> devices = DeviceManager.getDeviceList(DeviceInfo.FLAG_GET_ONLINE_DEVICE);
                    if(devices.size() == 0){
                        reply.writeString("false");
                    }

                    // 拉起界面
                    Operation start = new Intent.OperationBuilder()
                            .withDeviceId(devices.get(0).getDeviceId())
                            .withBundleName("com.myharos.fingerguessing")
                            .withAbilityName("com.myharos.fingerguessing.MainAbility")
                            .withFlags(Intent.FLAG_ABILITYSLICE_MULTI_DEVICE)
                            .build();
                    Intent startIntent = new Intent();
                    startIntent.setParam("toGame", true);
                    startIntent.setOperation(start);
                    context.startAbility(startIntent, 0);

                    // 连接对方设备的service
                    Intent connectIntent = new Intent();
                    Operation operation = new Intent.OperationBuilder()
                            .withDeviceId(devices.get(0).getDeviceId())
                            .withBundleName("com.myharos.fingerguessing")
                            .withAbilityName("com.myharos.fingerguessing.connect")
                            .withFlags(Intent.FLAG_ABILITYSLICE_MULTI_DEVICE)
                            .build();
                    connectIntent.setOperation(operation);
                    boolean connectRes = connectAbility(connectIntent, new IAbilityConnection() {
                        @Override
                        public void onAbilityConnectDone(ElementName elementName, IRemoteObject iRemoteObject, int i) {
                            // 连接成功
                            // 记录远程remote
                            otherRemote = iRemoteObject;
                            try {
                                // 向对方发送绑定信息，让对方也获取本端remote
                                MessageParcel data = MessageParcel.obtain();
                                //写入本端remote
                                data.writeRemoteObject(remote);
                                MessageParcel reply = MessageParcel.obtain();
                                MessageOption option = new MessageOption();
                                boolean t = otherRemote.sendRequest(4, data, reply, option);
                                reply.reclaim();
                                data.reclaim();
                            } catch (RemoteException e) {
                                System.out.println(e.toString());
                            }
                        }

                        @Override
                        public void onAbilityDisconnectDone(ElementName elementName, int i) {
                            System.out.println("disconnect");
                        }
                    });
                    reply.writeString("true");
                    break;
                }
                case 1:{
                    // subscribe
                    // FA订阅service，记录remote
                    System.out.println("subscribe");
                    localRemote = data.readRemoteObject();
                    reply.writeString("true");
                    break;
                }
                case 2:{
                    // get remote msg
                    // 收到来自对方设备的信息
                    try {
                        System.out.println("get remote msg:" + msg);
                        // 将信息发给FA
                        sendToFA(100, msg, localRemote);
                        reply.writeString("true");
                    }catch (Exception e){
                        System.out.println(e.toString());
                        reply.writeString("false");
                    }
                    break;
                }
                case 3:{
                    // send to remote
                    // 向对方设备发送信息
                    try {
                        System.out.println("send to remote:" + msg);
                        // 其实是发送给对方的service，对方service再发送给FA，我偷懒用了一个函数
                        sendToFA(2, msg, otherRemote);
                        reply.writeString("true");
                    }catch (Exception e){
                        System.out.println(e.toString());
                        reply.writeString("false");
                    }
                    break;
                }
                case 4:{
                    // bind remote
                    // 绑定对方远程remote
                    System.out.println("bind remote");
                    otherRemote = data.readRemoteObject();
                    System.out.println(otherRemote);
                }
                default:
                    return false;
            }
            return true;
        }
        @Override
        public IRemoteObject asObject() {
            return this;
        }
    }
}